package com.mishow.zxing.activity;

import java.io.IOException;
import java.util.Vector;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.mishow.R;
import com.mishow.activity.LoginActivity;
import com.mishow.activity.base.BaseActivity;
import com.mishow.bean.ScanCodeBean;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.CodeConstants;
import com.mishow.utils.Constants;
import com.mishow.widget.CustomDialog;
import com.mishow.zxing.camera.CameraManager;
import com.mishow.zxing.decoding.CaptureActivityHandler;
import com.mishow.zxing.decoding.InactivityTimer;
import com.mishow.zxing.view.ViewfinderView;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 作者：wei.miao <br/>
 * 描述：扫描条码界面
 */
public class CaptureActivity extends BaseActivity implements Callback,
		OnClickListener {
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private boolean vibrate;
	private static final float BEEP_VOLUME = 0.10f;
	private Button btn_open_light; // 开启关闭闪光灯
	private Button btn_back; // 返回按钮
	private EditText code_edit; // 邀请码编辑框
	private TextView title_tv; // 标题框
	private CustomDialog dialog; // 对话框
	private Button search_btn; // 搜索按钮
	private SharedPreferencesUtil userInfoPreference; // 用户相关信息
	private int userId; // 用户ID
	private int FromTag;// 标记进入扫描页面的来源 1-首页 2-药箱 3-注册 4-咨询
	private boolean islightOpen; // 灯光是否打开
	private SurfaceView surfaceView; // 绘制页面

	public static final int FROM_HOME_PAGE = 1; // 标记入口1-首页
	public static final int FROM_MEDICINE_KIT = 2; // 标记入口2-药箱
	public static final int FROM_REGIST = 3; // 标记入口3-注册
	public static final int FROM_ASK = 4; // 标记从咨询进入
	private boolean isEdit; // 标记是否在编辑邀请码界面

	/** Called when the activity is first created. */
	@Override
	protected void initData() {
		Intent intent = getIntent();
		FromTag = intent.getIntExtra("FromTag", -1);

		userInfoPreference = new SharedPreferencesUtil(this);
		if (userInfoPreference.getLoginState()
				&& userInfoPreference.getUserId() != null) { // 如果已经登录直接获取userID
			userId = Integer.parseInt(userInfoPreference.getUserId());
		}
		CameraManager.init(this);
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.capture);
		viewfinderView = (ViewfinderView) this
				.findViewById(R.id.viewfinder_view);
		btn_back = (Button) findViewById(R.id.btn_back);
		btn_open_light = (Button) findViewById(R.id.btn_open_light);
		code_edit = (EditText) findViewById(R.id.code_edit);
		title_tv = (TextView) findViewById(R.id.title_tv);
		search_btn = (Button) findViewById(R.id.search_btn);
	}

	@Override
	protected void setAttribute() {
		switch (FromTag) {
		case FROM_REGIST: // 注册入口

		case FROM_MEDICINE_KIT: // 家庭药箱
			code_edit.setVisibility(View.GONE);
			title_tv.setVisibility(View.VISIBLE);
			break;
		case FROM_HOME_PAGE: // 首页入口
			code_edit.setVisibility(View.VISIBLE);
			title_tv.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		btn_back.setOnClickListener(this);
		btn_open_light.setOnClickListener(this);
		code_edit.setOnClickListener(this);
		search_btn.setOnClickListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();
		surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * Handler scan result
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();
		String resultString = result.getText();
		// FIXME
		if (resultString.equals("")) {
			Toast.makeText(CaptureActivity.this, R.string.scan_default,
					Toast.LENGTH_SHORT).show();
			scanFailedOrError();
		} else {
			handleResult(result);
		}
	}

	/**
	 * 扫描失败或者不是规定的二维码、条码，当前处理关闭扫码界面
	 */
	private void scanFailedOrError() {
		this.finish();
	}
	
	/**
	 * 扫描结果处理方法
	 * 
	 * @param result
	 */
	public void handleResult(Result result) {
		String resultString = result.getText();
		
		switch (FromTag) {
		case FROM_HOME_PAGE: // 首页入口
			if ("QR_CODE".equals(result.getBarcodeFormat().name())) {
				isKKmyQrcode(resultString);
			} else { // 电子监管码
				if (resultString.length() > 13) {
					Toast.makeText(CaptureActivity.this, R.string.toast_string,
							Toast.LENGTH_SHORT).show();
					restartDecode();
//					scanFailedOrError();
				} else { // 药品条形码

					//doGetSearchDrugCategory(resultString ,SearchResultActivity.SEARCH_TYPE_KEYWORD);
					
				}
			}
			break;
		case FROM_MEDICINE_KIT: // 家庭药箱入口
			if ("QR_CODE".equals(result.getBarcodeFormat().name())) {
				Toast.makeText(CaptureActivity.this, "请扫描药品条形码",
						Toast.LENGTH_SHORT).show();
				restartDecode();
//				scanFailedOrError();
			} else {
				if (resultString.length() > 13) {
					Toast.makeText(CaptureActivity.this, R.string.toast_string,
							Toast.LENGTH_SHORT).show();
					restartDecode();
//					scanFailedOrError();
				} else {
					//doGetSearchDrugCategory(resultString ,SearchResultActivity.SEARCH_TYPE_KEYWORD);
				}
			}
			break;
		case FROM_REGIST: // 注册入口
			if ("QR_CODE".equals(result.getBarcodeFormat().name())) {
				ScanCodeBean codebean;
				codebean = AndroidUtil.scanResult(resultString);

				if (codebean.getCodeType() == CodeConstants.USER_CODE_TYPE
						|| codebean.getCodeType() == CodeConstants.DY_CODE_TYPE
						|| codebean.getCodeType() == CodeConstants.MERCHANT_CODE_TYPE) {
					String code = codebean.getCode(); // 获取邀请码(无type属性)
					Intent intent = new Intent();
					intent.putExtra("qrCode", code);
					setResult(RESULT_OK, intent);
					CaptureActivity.this.finish();
				} else {
					Toast.makeText(CaptureActivity.this,
							getString(R.string.error_qrcode),
							Toast.LENGTH_SHORT).show();
					scanFailedOrError();
				}
			} else {
				Toast.makeText(CaptureActivity.this,
						getString(R.string.error_qrcode), Toast.LENGTH_SHORT)
						.show();
				scanFailedOrError();
			}
			break;

		case FROM_ASK: // 从咨询界面进入
			if ("QR_CODE".equals(result.getBarcodeFormat().name())) {
				ScanCodeBean codebean;
				codebean = AndroidUtil.scanResult(resultString);
				if (!userInfoPreference.getLoginState()) { // 用户没有登陆
					doLogin();
					return;
				}
				if (codebean.getCodeType() == CodeConstants.DY_CODE_TYPE) { // 如果是店员邀请码
					dogetStaffByCode(true, codebean.getCode());
				} else {
					Toast.makeText(CaptureActivity.this,
							getString(R.string.error_qrcode),
							Toast.LENGTH_SHORT).show();
					scanFailedOrError();
				}
			} else {
				Toast.makeText(CaptureActivity.this,
						getString(R.string.error_qrcode), Toast.LENGTH_SHORT)
						.show();
				scanFailedOrError();
			}
			break;

		default:
			break;
		}

	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
			if (handler == null) {
				handler = new CaptureActivityHandler(this, decodeFormats,
						characterSet);
			}
		} catch (IOException ioe) {

			return;
		} catch (RuntimeException e) {
			CustomDialog dialog = new CustomDialog(this, false);
			dialog.setCancelable(false);
			dialog.setTitleContent("温馨提示", "无法获取摄像头数据，请检查是否已经打开摄像头权限。");
			dialog.setPositiveButton(getString(R.string.confirm_string),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							CaptureActivity.this.finish();
						}
					});
			dialog.show();
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;

	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();

	}

	// 扫描完成是的提示音
	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	/**
	 * 物理返回键
	 */
	@Override
	public void onBackPressed() {
		if (isEdit) { // 在编辑界面点击物理返回后的操作处理
			surfaceView = (SurfaceView) findViewById(R.id.preview_view);
			SurfaceHolder surfaceHolder = surfaceView.getHolder();
			if (hasSurface) {
				initCamera(surfaceHolder);
			} else {
				surfaceHolder.addCallback(this);
			}
			decodeFormats = null;
			characterSet = null;
			code_edit.setText("");
			surfaceView.setVisibility(View.VISIBLE);
			viewfinderView.setVisibility(View.VISIBLE);
			btn_open_light.setVisibility(View.VISIBLE);
			search_btn.setVisibility(View.GONE);
			isEdit = false;
		} else {
			if (FromTag == FROM_HOME_PAGE) {// 从首页或问专家界面进入
				setResult(RESULT_OK);
				finish();
			} else {
				finish();
			}
		}
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_back:
			if (FromTag == FROM_HOME_PAGE) {// 从首页或问专家界面进入
				setResult(RESULT_OK);
				finish();
			} else {
				finish();
			}
			break;
		case R.id.btn_open_light:
			if (!islightOpen) {
				CameraManager.get().startTorch();
				islightOpen = true;
				btn_open_light.setSelected(islightOpen);
			} else {
				CameraManager.get().stopTorch();
				islightOpen = false;
				btn_open_light.setSelected(islightOpen);
			}
			break;
		case R.id.code_edit:
			if (handler != null) {
				handler.quitSynchronously();
				handler = null;
			}
			CameraManager.get().closeDriver();
			surfaceView.setVisibility(View.GONE);
			viewfinderView.setVisibility(View.GONE);
			btn_open_light.setVisibility(View.GONE);
			search_btn.setVisibility(View.VISIBLE);
			isEdit = true;
			break;
		case R.id.search_btn: // 输入二维码搜索
			String inviteCode = code_edit.getText().toString().trim();
			if (inviteCode != null && inviteCode.length() == 6) { // 长度为6判断为店员邀请码
				dogetStaffByCode(true, inviteCode);
			} else if (inviteCode != null && inviteCode.length() == 8 && FromTag != FROM_ASK) { // 长度为8判断为药店邀请码
				dogetIntoDrugInfo(inviteCode);
			} else {
				if (FromTag != FROM_ASK) {
					Toast.makeText(CaptureActivity.this,
							getString(R.string.edit_code), Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(CaptureActivity.this,
							getString(R.string.edit_code_ask), Toast.LENGTH_SHORT)
							.show();
				}
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 根据不同二维码做出对应操作
	 */
	public void isKKmyQrcode(String code) {
		ScanCodeBean codebean;
		codebean = AndroidUtil.scanResult(code);
		if (codebean.getCodeType() == CodeConstants.DY_CODE_TYPE) { // 店员邀请码
			if (!userInfoPreference.getLoginState()) { // 用户没有登陆
				doLogin();
				return;
			} else {
				doNotice(codebean.getCode());
			}
		} else if (codebean.getCodeType() == CodeConstants.MERCHANT_CODE_TYPE) {
			dogetIntoDrugInfo(codebean.getCode()); // 药店二维码 获取id,跳转微店界面
		} else {
			Toast.makeText(CaptureActivity.this,
					getString(R.string.error_qrcode), Toast.LENGTH_SHORT)
					.show();
			scanFailedOrError();
		}
	}

	/**
	 * 扫码关注判断用户没有登陆处理
	 */
	public void doLogin() {
		dialog = new CustomDialog(CaptureActivity.this, true);
		dialog.setTitleContent(null, "登录后才能关注药师哦");
		dialog.setPositiveButton(getString(R.string.dialog_confirm),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(CaptureActivity.this,
								LoginActivity.class);
						startActivityForResult(intent,Constants.REQUESTCODE_LOGIN);
						dialog.dismiss();
						restartDecode();
					}
				});
		dialog.setNagetiveButton(getString(R.string.dialog_cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						restartDecode();
					}
				});
		dialog.show();
	}

	/**
	 * 重新扫描
	 */
	private void restartDecode() {
		if (handler == null) {
			return;
		}
		Message message = new Message();
		message.what = R.id.restart_preview;
		handler.handleMessage(message);
	}
	
	/**
	 * startActivityForResult返回处理
	 */
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case Constants.REQUESTCODE_LOGIN:
				if (userInfoPreference.getLoginState()
						&& userInfoPreference.getUserId() != null) { // 如果已经登录直接获取userID
					userId = Integer.parseInt(userInfoPreference.getUserId());
				}
				break;
			default:
				break;

			}
		}
	}

	/**
	 * 扫描关注请求
	 * 
	 * @param code
	 */
	public void doNotice(String code) {
		/*if (!AndroidUtil.isNetworkAvailable(this)) { // 无网络连接
			Toast.makeText(CaptureActivity.this, R.string.no_connector,
					Toast.LENGTH_SHORT).show();
			scanFailedOrError();
		} else {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put("userId", userId);
			params.put("type", 0);// 0-关注，1-取消关注
			params.put("recommandCode", code);
			String url = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.MERCHANTSTAFF_FOLLOW);
			Map<String, String> lastParams = NetworkUtil.generaterPostRequestParams(this, params);
			OnResponseListener<NoticeResultBean> listener = new OnResponseListener<NoticeResultBean>(this) {
				
				@Override
				public void onSuccess(NoticeResultBean response) {
					Toast.makeText(CaptureActivity.this, R.string.tip_notice_success, Toast.LENGTH_SHORT).show();
					int merchantStaffId = response.getBody().getResult().getMerchantStaffId();
					// 跳转到个人信息页
					PersonalInfoActivity.intoActivity(CaptureActivity.this, merchantStaffId,
							PersonalInfoActivity.FROM_CAPTURE);
					
					CaptureActivity.this.finish();
				}
				
				@Override
				public void onError(String code, String message) {
					Toast.makeText(CaptureActivity.this, message, Toast.LENGTH_SHORT).show();
					scanFailedOrError();
				}
				
				@Override
				public void onCompleted() {
				}
			};
			executeRequest(
					new FastJsonRequest<NoticeResultBean>(Method.POST, url, NoticeResultBean.class, listener, listener)
							.setParams(lastParams));
		}*/
	}

	/**
	 * 根据邀请码来搜索店员
	 */
	public void dogetStaffByCode(boolean isProgressShow, String inviteCode) {

		/*if (!AndroidUtil.isNetworkAvailable(this)) { // 无网络连接
			Toast.makeText(this, R.string.no_connector, Toast.LENGTH_LONG)
					.show();
			return;
		}
		if (isProgressShow) {
			showProgress("", getString(R.string.loading), true);
		}
		Map<String, String> params = new HashMap<String, String>();
		params.put("inviteCode", inviteCode); // 邀请码
		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(this, params);
		String url = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.GET_STAFF_BYCODE);
		OnResponseListener<GetStaffBean> listener = new OnResponseListener<GetStaffBean>(this) {
			
			@Override
			public void onSuccess(GetStaffBean response) {
				int merchantStaffId = response.getBody().getResult().getStaffId();
				if (merchantStaffId != 0) {
					PersonalInfoActivity.intoActivity(CaptureActivity.this, merchantStaffId,
							PersonalInfoActivity.FROM_CAPTURE);
				} else {
					Toast.makeText(CaptureActivity.this, getString(R.string.no_find_DY), Toast.LENGTH_SHORT).show();
				}
			}
			
			@Override
			public void onError(String code, String message) {
				if (code.equals(OnResponseListener.ERROR_CODE_SYSTEM)) {
					Toast.makeText(CaptureActivity.this, getString(R.string.error_data_string), Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(CaptureActivity.this, R.string.no_find_DY, Toast.LENGTH_SHORT).show();
				}
				dismissProgress();
				scanFailedOrError();
			}
			
			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<GetStaffBean>(Method.POST, url, GetStaffBean.class, listener, listener)
				.setParams(lastParams), null);*/
	}

	/**
	 * 
	 * @param recommandcode
	 *            扫描二维码（药店二维码）
	 */
	private void dogetIntoDrugInfo(String recommandcode) {/*
		HashMap<String, String> params = new HashMap<String, String>();
		if (userInfoPreference.getLoginState()) { // 用户已经登陆
			params.put("userId", userInfoPreference.getUserId());
		}
		params.put("recommandCode", recommandcode);
		Map<String, String> requestParams = NetworkUtil
				.generaterPostRequestParams(this, params);
		String url = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.COLLECT_MERCHANT);
		showProgress("", "", true);
		OnResponseListener<ScanQrcodeBean> listener = new OnResponseListener<ScanQrcodeBean>(this) {
			
			@Override
			public void onSuccess(ScanQrcodeBean response) {
				if (response.getBody().getResult() != null) {
					DrugShopInfoActivity.intoActivity( // 跳转到微店界面
							CaptureActivity.this, response.getBody().getResult().getMerchantId());
				}
			}
			
			@Override
			public void onError(String code, String message) {
				dismissProgress();
				Toast.makeText(CaptureActivity.this, message, Toast.LENGTH_SHORT).show();
				scanFailedOrError();
			}
			
			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<ScanQrcodeBean>(Method.POST, url, ScanQrcodeBean.class, listener, listener)
				.setParams(requestParams));
	*/}
	
	/**
	 * 获取全部分类与排序列表(扫描跳转)
	 */
	private void doGetSearchDrugCategory(String keyword,int searchType ) {/*
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("keyWord", keyword);
		params.put("serchType", searchType+"");
		params.put("sortType", "0");
		String url = HttpUrlConstant.getPostUrl(this, HttpUrlConstant.SEARCH_RESULT_LIST);
		Map<String, String> requestParams = NetworkUtil.generaterPostRequestParams(this, params);
		OnResponseListener<DrugsBean> listener = new OnResponseListener<DrugsBean>(this) {
			
			@Override
			public void onSuccess(DrugsBean response) {
				List<DrugInfo> results = response.getBody().getResult().getDataList();
				if (results!=null&&results.size()!=0) {
					Intent intent = new Intent(CaptureActivity.this, MedicineDetailScrollActivity.class);
					intent.putExtra("drugId", results.get(0).getNrId());
					intent.putExtra("drugName", results.get(0).getNrName());
					startActivity(intent);
					CaptureActivity.this.finish();
				}else {
					Toast.makeText(CaptureActivity.this, "扫描失败，请重试", 0).show();
				}
				
			}
			
			@Override
			public void onError(String code, String message) {
				Toast.makeText(CaptureActivity.this, "扫描失败，请重试", 0).show();
			}
			
			@Override
			public void onCompleted() {
			}
		};
		executeRequest(new FastJsonRequest<DrugsBean>(Method.POST, url, DrugsBean.class, listener, listener)
				.setParams(requestParams));
	*/}

}